package jsf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import jpa.entities.StudentCourse;
import jsf.util.JsfUtil;
import jsf.util.PaginationHelper;
import jsf.session.StudentCourseFacade;

import java.io.Serializable;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.ServletContext;
import jpa.entities.Course;
import jpa.entities.Staff;
import jpa.entities.StudentCoursePK;
import jpa.entities.Students;
import org.primefaces.model.UploadedFile;

@ManagedBean(name = "studentCourseController")
@SessionScoped
public class StudentCourseController implements Serializable {

    private StudentCourse current;
    private DataModel items = null;
    @EJB
    private jsf.session.StudentCourseFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private UploadedFile file;
    private String destination = "uploaded";
    
    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }
    
    public StudentCourseController() {
    }

    public StudentCourse getSelected() {
        if (current == null) {
            current = new StudentCourse();
            current.setStudentCoursePK(new jpa.entities.StudentCoursePK());
            selectedItemIndex = -1;
        }
        return current;
    }

    private StudentCourseFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (StudentCourse) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }
    public String findAllCourseByTopicIdForUser() {
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            Students student = (Students) context.getExternalContext().getSessionMap().get("IsStudent");
            items = new ListDataModel(ejbFacade.GetListAssignmentOfStudent(student.getUserName()));
            return "/faces/user/studentCourse/List.xhtml";

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
    private String nameSearch;

    public String getNameSearch() {
        return nameSearch;
    }

    public void setNameSearch(String nameSearch) {
        this.nameSearch = nameSearch;
    }
    
    public String SearchByCourseName()
    {
        items = nameSearch !=null ? new ListDataModel(ejbFacade.SearchCourseByName(nameSearch)) : new ListDataModel(ejbFacade.SearchCourseByName(""));
        return "/faces/admin/studentCourse/List.xhtml";
    }
    private Course course123;

    public Course getCourse123() {
        return course123;
    }

    public void setCourse123(Course course123) {
        this.course123 = course123;
    }
    
    public String GetListAssignmentOfStudentByCourseName()
    {
        items = new ListDataModel(ejbFacade.GetListAssignmentOfStudentByCourseName(course123));
        return "/faces/admin/studentCourse/List.xhtml";
    }
//    public String prepareViewForUser()
//    {
//        current = (StudentCourse) getFacade().GetProfile("tuanvn");
//        return "/faces/user/studentCourse/View.xhtml";
//    }
    public String prepareCreate() {
        current = new StudentCourse();
        current.setStudentCoursePK(new jpa.entities.StudentCoursePK());
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("StudentCourseCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (StudentCourse) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public StudentCourse AddCurrentStudentAndCourse()
    {
        FacesContext context = FacesContext.getCurrentInstance();
        Students student = (Students) context.getExternalContext().getSessionMap().get("IsStudent");
        Course course = (Course) context.getExternalContext().getSessionMap().get("CurrentCourse");
        StudentCourse studentcourseCurrent = getFacade().addStudentCourseValid(student, course);;
        return studentcourseCurrent;
    }
    public StudentCourse UpdateCurrentStudentAndCourse()
    {
        FacesContext context = FacesContext.getCurrentInstance();
        Students student = (Students) context.getExternalContext().getSessionMap().get("IsStudent");
        Course course = (Course) context.getExternalContext().getSessionMap().get("CurrentCourse");
        StudentCourse studentcourseCurrent = getFacade().checkStudentCourseValid(student.getUserName(), course.getCourseName());
        return studentcourseCurrent;
    }
    //admin
    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("StudentCourseUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }
    //GUI
    public String UpdateForUser() {
        try {
            if(UpdateCurrentStudentAndCourse() != null)
            {
                current = UpdateCurrentStudentAndCourse();
                StudentcopyFile(file.getFileName(), file.getInputstream());
                current.setFileUpload(file.getFileName());
                getFacade().edit(current);
            }
            else
            {
                current = AddCurrentStudentAndCourse();
                StudentcopyFile(file.getFileName(), file.getInputstream());
                current.setFileUpload(file.getFileName());
                getFacade().create(current);
            }
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("StudentCourseCreated"));
            return "/faces/user/course/View.xhtml";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }
    public String destroy() {
        current = (StudentCourse) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("StudentCourseDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }
    public boolean NoLogin() {
            FacesContext context = FacesContext.getCurrentInstance();
            Students student = (Students) context.getExternalContext().getSessionMap().get("IsStudent");
            if (student == null) {
                return true;
            }
            return false;
    }
    public void StudentcopyFile(String fileName, InputStream in) {
        try {

            ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance()
                    .getExternalContext().getContext();
            String realPath = ctx.getRealPath("/");
            File theDir = new File(realPath + "\\" + destination);
            // if the directory does not exist, create it
            if (!theDir.exists()) {
                boolean result = theDir.mkdir();
                if (result) {
                    System.out.println("DIR created");
                }

            }
            // write the inputStream to a FileOutputStream
            OutputStream out = new FileOutputStream(new File(theDir + "\\" + fileName));

            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            in.close();
            out.flush();
            out.close();

            System.out.println("New file created!");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        //items = (DataModel)getFacade().GetProfile("tuanvn");
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = StudentCourse.class)
    public static class StudentCourseControllerConverter implements Converter {

        private static final String SEPARATOR = "#";
        private static final String SEPARATOR_ESCAPED = "\\#";

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            StudentCourseController controller = (StudentCourseController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "studentCourseController");
            return controller.ejbFacade.find(getKey(value));
        }

        jpa.entities.StudentCoursePK getKey(String value) {
            jpa.entities.StudentCoursePK key;
            String values[] = value.split(SEPARATOR_ESCAPED);
            key = new jpa.entities.StudentCoursePK();
            key.setStudentId(Integer.parseInt(values[0]));
            key.setCourseId(Integer.parseInt(values[1]));
            return key;
        }

        String getStringKey(jpa.entities.StudentCoursePK value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value.getStudentId());
            sb.append(SEPARATOR);
            sb.append(value.getCourseId());
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof StudentCourse) {
                StudentCourse o = (StudentCourse) object;
                return getStringKey(o.getStudentCoursePK());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + StudentCourse.class.getName());
            }
        }
    }
}
